package webv1

import (
	"encoding/base64"
	"github.com/gin-gonic/gin"
	"myCloud/embed"
	"myCloud/utils"
	"net/http"
	"path/filepath"
	"strings"
)

var notFound = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Not Found</title>
</head>
<body>
    <h1>File Not Found</h1>
</body>
</html>`

/*
提供给用户的web页面，功能介绍，APP下载
*/
func webPageApiInit(r *gin.RouterGroup) {
	r.GET("/portal/*file", webPageIndexHandler)
	r.GET("/app.apk", appDownloadHandler)
	r.GET("/server_qr.png", serverQrHandler)
}

func appDownloadHandler(c *gin.Context) {
	filePath := "/portal/public/static/app.apk"
	data, err := embed.FSByte(false, filePath)
	if err != nil {
		c.Data(http.StatusNotFound, "text/html", []byte(notFound))
		return
	}

	cType := "application/octet-stream"
	c.Data(http.StatusOK, cType, data)
}

func webPageIndexHandler(c *gin.Context) {
	filePath := c.Param("file")
	if strings.HasPrefix(filePath, "/") {
		filePath = filePath[1:]
	}
	if len(filePath) == 0 {
		filePath = "index.html"
	}

	fullPath := filepath.ToSlash(filepath.Join("/portal/public", filePath))
	data, err := embed.FSByte(false, fullPath)
	if err != nil {
		c.Data(http.StatusNotFound, "text/html", []byte(notFound))
		return
	}

	c.Data(http.StatusOK, "", data)
}

func serverQrHandler(c *gin.Context) {
	v, err := utils.GetInterfacesQrData()
	if err!= nil {
		abReq(c, http.StatusInternalServerError, "查找服务器网卡列表失败", err)
		return
	}

	logo, err := embed.FSByte(false, "/portal/public/images/qrlogo.png")
	if err != nil {
		abReq(c, http.StatusInternalServerError, "未找到 logo", err)
		return
	}

	out, err := utils.NewQrcode(base64.StdEncoding.EncodeToString(v), logo)
	if err != nil {
		abReq(c, http.StatusInternalServerError, "二维码生成失败", err)
		return
	}

	c.Data(http.StatusOK, "image/png", out)
}
